<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta
          name="viewport"
          content="width=device-width,
height=device-height, initial-scale=1,
maximum-scale=1, minimum-scale=1, user-scalable=no"/>
  <title>TyrantGenesis 自制播放器</title>
  <link rel="stylesheet" href="css/aliplayer-min.css">
  <style>
    html, body {
      margin: 0;
      height: 100%;
      overflow: hidden;
    }
    .box {
      display: flex;
      flex-direction: column;
      height: 100%;
    }
    .player {
      height: 273px;
    }
    .barrage-scroll {
      height: calc(100% - 300px);
      overflow-y: auto;
    }
    .barrage-item {
      padding: 4px 12px;
      font-size: 14px;
      line-height: 30px;
    }
    .avatar {
      position: relative;
      top: 7px;
      width: 24px;
      height: 24px;
      border-radius: 50%;
      margin-right: 6px;
    }
    .username {
      color: #999;
      margin-right: 16px;
    }
    .content {
      color: #333;
    }
  </style>
</head>
<body>
<div class="box">
  <div class="prism-player player" id="player-con"></div>
  <div class="barrage-scroll" id="app">
    <div class="barrage-item" v-for="item in dataList">
      <img class="avatar" :src="item.avatar" alt="" /><span class="username">{{item.user}}:</span><span class="content">{{item.content}}</span>
    </div>
  </div>
</div>

<!--<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>-->
<script src="js/aliplayer-min.js"></script>
<script src="utils/huya_lib.js"></script>
<script src="js/vue.min.js"></script>
<script>
  const getQueryVariable = variable => {
    let query = window.location.search.substring(1)
    let vars = query.split("&");
    for (let i=0;i<vars.length;i++) {
      let pair = vars[i].split("=");
      if(pair[0] === variable) return pair[1]
    }
    return false
  }

  const rid = getQueryVariable('rid')
  const source = decodeURIComponent(getQueryVariable('source'))
  const info = JSON.parse(decodeURIComponent(getQueryVariable('info')))

  const player = new Aliplayer({
      "id": "player-con",
      "source": source,
      "width": "100%",
      // "height": "500px",
      "autoplay": true,
      "isLive": true,
      "rePlay": false,
      "playsinline": true,
      "preload": true,
      "controlBarVisibility": "hover",
      "useH5Prism": true
    }, function (player) {
      console.log("The player is created");
    }
  );
</script>
<script>
  const url = "wss://cdnws.api.huya.com/"
  new Vue({
    el: '#app',
    data() {
      return {
        ws: null,
        room_id: rid,
        _info: null,
        _main_user_id: null,
        _ping_timer: null,
        dataList: [],
      }
    },
    mounted() {
      this._info = info
      this._main_user_id = new HUYA.UserId()
      this._main_user_id.lUid = this._info.yyuid
      this._main_user_id.sHuYaUA = "webh5&1.0.0&websocket"

      this.ws = new WebSocket(url)
      this.ws.onopen = (res, err) => {
        this._get_chat_list();
        this._ping_timer = setInterval(this.sendPingReq.bind(this), 30 * 1000)
      }
      this.ws.onmessage = this._on_mes.bind(this)
    },
    methods: {
      _get_chat_info() {
        try {
          /*$.ajax({
            url: `https://m.huya.com/${this.room_id}`,
            success: result => {
              console.log(result)
            }
          });
          // let body = r({
          //   url:
          // });
          let info = {};
          let subsid_array = window.body.match(/var SUBSID = '(.*)';/);
          let topsid_array = window.body.match(/var TOPSID = '(.*)';/);
          let yyuid_array = window.body.match(/ayyuid: '(.*)',/);
          let anthor_nick = window.body.match(/var ANTHOR_NICK = '(.*)';/)
          if (!subsid_array || !topsid_array || !yyuid_array) {
            return;
          }
          info.subsid = subsid_array[1] === '' ? 0 : parseInt(subsid_array[1]);
          info.topsid = topsid_array[1] === '' ? 0 : parseInt(topsid_array[1]);
          info.yyuid = parseInt(yyuid_array[1]);
          info.sGuid = "";
          info.anthor_nick = anthor_nick[1] === '' ? '' : anthor_nick[1];*/
          let info = {};
          info.subsid = "367138632";
          info.topsid = "367138632";
          info.yyuid = "367138632";
          info.sGuid = "";
          info.anthor_nick = '卡尔';
          return info
        } catch (e) {
          console.log(e)
        }
      },
      _get_chat_list() {
        let t;
        (t = new HUYA.WSRegisterGroupReq).vGroupId.value.push("live:" + this._info.yyuid),
                t.vGroupId.value.push("chat:" + this._info.yyuid);
        let e = new Taf.JceOutputStream;
        t.writeTo(e);
        let i = new HUYA.WebSocketCommand;
        i.iCmdType = HUYA.EWebSocketCommandType.EWSCmdC2S_RegisterGroupReq,
                i.vData = e.getBinBuffer(),
                e = new Taf.JceOutputStream,
                i.writeTo(e);
        this.ws.send(e.getBuffer())
      },
      sendPingReq() {
        let currTime = Date.now();
        let i = new HUYA.VideoGatewayProxy2VGPingReq();
        i.lLocalTime = .001 * currTime >> 0;
        this._send_wup('videogateway', 'videoGatewayProxy2VGPing', i);
      },
      _send_wup(action, callback, req) {
        try {
          let wup = new Taf.Wup()
          wup.setServant(action)
          wup.setFunc(callback)
          wup.writeStruct("tReq", req)
          let command = new HUYA.WebSocketCommand()
          command.iCmdType = HUYA.EWebSocketCommandType.EWSCmd_WupReq
          command.vData = wup.encode()
          let stream = new Taf.JceOutputStream()
          command.writeTo(stream)
          this.ws.send(stream.getBuffer())
        } catch (err) {
          console.log(err)
        }
      },
      _on_mes(data) {
        let self = this
        try {
          let fr
          fr = new FileReader();
          fr.onload = function() {
            let data = this.result
            let stream = new Taf.JceInputStream(data);
            let command = new HUYA.WebSocketCommand();
            command.readFrom(stream);
            // console.log(command)
            switch (command.iCmdType) {
              /*case HUYA.EWebSocketCommandType.EWSCmd_WupRsp:
                try{
                  let wup = new Taf.Wup()
                  wup.decode(command.vData.buffer)
                  let map = new (TafMx.WupMapping[wup.sFuncName])()
                  wup.readStruct('tRsp', map, TafMx.WupMapping[wup.sFuncName])
                  this._emitter.emit(wup.sFuncName, map)
                }catch (e) {
                  console.log(e)
                }
                break*/
              case HUYA.EWebSocketCommandType.EWSCmdS2C_MsgPushReq:
                stream = new Taf.JceInputStream(command.vData.buffer);
                let msg = new HUYA.WSPushMessage();
                msg.readFrom(stream);
                stream = new Taf.JceInputStream(msg.sMsg.buffer);
                if (TafMx.UriMapping[msg.iUri]) {
                  let map = new (TafMx.UriMapping[msg.iUri])();
                  map.readFrom(stream);
                  if (map.sContent !== undefined){
                    self.dataList.push({
                      avatar: map.tUserInfo.ic,
                      user: map.tUserInfo.sNickName,
                      content: map.sContent,
                    })

                    let ele = document.getElementById('app');
                    ele.scrollTop = ele.scrollHeight;
                  }
                }
                break;
              /*case HUYA.EWebSocketCommandType.EWSCmdS2C_VerifyCookieRsp:
                stream = new Taf.JceInputStream(command.vData.buffer);
                let g = new HUYA.WSVerifyCookieRsp;
                g.readFrom(stream);
                this.isLogin = g.iValidate == 0;
                if(this.isLogin){
                  log.info(this.getInfo()+"登录成功");
                  this.emit("loginSuccess");
                  this._heartbeat();
                  this._heartbeat_timer = setInterval(this._heartbeat.bind(this), heartbeat_interval)
                }else{
                  log.info(this.getInfo()+"登录失败");
                  this.emit("loginFail");
                  this.isRun = false;
                  this.exit();
                }
                break;*/
              default:
                break
            }
          }
          fr.readAsArrayBuffer(data.data);
        } catch (e) {
          console.log(e)
        }
      },
    }
  })
</script>
</body>
</html>